package com.gjd.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.gjd.config.AlipayConfig;
import com.gjd.domain.ResponseResult;
import com.gjd.domain.entity.Orders;
import com.gjd.domain.entity.PayRecord;
import com.gjd.domain.entity.PayStatus;
import com.gjd.domain.vo.PayRecordVo;
import com.gjd.mapper.PayMapper;
import com.gjd.service.PayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.gjd.config.AlipayConfig.ALIPAY_PUBLIC_KEY;

@Api(value = "订单支付接口", tags = "订单支付接口")
@Slf4j
@Controller
@RequestMapping("/user/pay")
public class PayController {

    @Autowired
    private PayService payService;


    @ApiOperation("生成支付二维码")
    @PostMapping("/generatePayCode")
    @ResponseBody
    public ResponseResult generatePayCode(@RequestBody Orders orders) {
        return payService.operateOrders(orders);
    }


    @ApiOperation("扫码下单接口")
    @GetMapping("/requestPay")
    public void requestPay(String payNo, HttpServletResponse httpResponse) throws IOException, AlipayApiException {
        //校验支付记录交易号是否存在
        PayRecord payRecord = payService.getPayRecordByPayNo(payNo);
        if (payRecord == null) {
            return;
        }
        //获得初始化的AlipayClient
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
        //创建API对应的request
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        //告诉支付宝支付结果通知的地址
//        alipayRequest.setNotifyUrl("https://tjxt-user-t.itheima.net/notify_url.php");
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        //填参数
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\""+payRecord.getPayNo()+"\"," +
                "    \"total_amount\":"+payRecord.getTotalPrice()+"," +
                "    \"subject\":\""+payRecord.getOrderName()+"\"," +
                "    \"product_code\":\"QUICK_WAP_WAY\"" +
                "  }");
        String form = client.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
    }


    @ApiOperation("支付通知")
    @RequestMapping("/receiveNotify")
    public void receiveNotify(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //验签
        boolean verify_result = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");

        if(verify_result){//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
            //appid
            String appid = new String(request.getParameter("app_id").getBytes("ISO-8859-1"),"UTF-8");
            //总金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            if(trade_status.equals("TRADE_SUCCESS")){
                PayStatus payStatus = new PayStatus();
                payStatus.setAppId(appid);
                payStatus.setTradeStatus(trade_status);
                payStatus.setOutTradeNo(out_trade_no);
                payStatus.setTotalPrice(total_amount);
                payStatus.setTradeNo(trade_no);
                payService.saveAliPayStatus(payStatus);
            }
            response.getWriter().println("success");

        }else{
            //验证失败
            response.getWriter().println("fail");
        }
    }


}
